<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" class="search-form">
        <el-row :gutter="20">
          <el-col :span="4">
            <el-form-item label="记录类型" prop="recordType">
              <el-select v-model="searchForm.recordType" placeholder="请选择记录类型" style="width: 100%">
                <el-option label="交班记录" :value="1" />
                <el-option label="接班记录" :value="2" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="班次">
              <el-select v-model="searchForm.shiftId" placeholder="请选择班次" clearable style="width: 100%">
                <el-option v-for="item in classesOptions" :key="item.departmentId" :label="item.classesName"
                  :value="item.departmentId" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="交接状态">
              <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 100%">
                <el-option label="待确认" :value="0" />
                <el-option label="已确认" :value="1" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="交接日期">
              <el-date-picker v-model="searchForm.handoverTime" type="date" placeholder="选择交接日期"
                value-format="YYYY-MM-DD" style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <div class="form-actions">
              <el-button type="primary" @click="handleSearch" :loading="loading">
                <el-icon class="el-icon--left">
                  <Search />
                </el-icon>
                查询
              </el-button>
              <el-button @click="resetSearch">
                <el-icon class="el-icon--left">
                  <Refresh />
                </el-icon>
                重置
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="table-card mt-2">
      <div class="action-buttons">
        <el-button type="primary" @click="handleAdd">
          <el-icon class="el-icon--left">
            <Plus />
          </el-icon>
          新增记录
        </el-button>
        <!-- <el-button type="warning" @click="handleBatchDelete" :disabled="selectedRows.length === 0">
          <el-icon class="el-icon--left">
            <Delete />
          </el-icon>
          批量删除
        </el-button>
        <el-button type="success" @click="handleBatchConfirm" :disabled="selectedRows.length === 0">
          <el-icon class="el-icon--left">
            <Check />
          </el-icon>
          批量确认
        </el-button> -->
      </div>

      <el-table :data="tableData" border style="width: 100%"
        @selection-change="handleSelectionChange" class="mt-2">
        <el-table-column type="selection" width="55" align="center" />

        <el-table-column prop="changeShiftsId" label="记录ID" align="center"/>

        <el-table-column prop="shiftOutDispatcherName" label="交班人员" align="center">
          <template #default="{ row }">
            <span>{{ row.shiftOutDispatcherName || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="shiftInDispatcherName" label="接班人员" align="center">
          <template #default="{ row }">
            <span>{{ row.shiftInDispatcherName || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="className" label="班次" align="center">
          <template #default="{ row }">
            <span>{{ getClassName(row.shiftId) || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="handoverTime" label="交接时间" align="center">
          <template #default="{ row }">
            <span>{{ formatDateTime(row.handoverTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="handoverContent" label="交接内容" align="center" show-overflow-tooltip>
          <template #default="{ row }">
            <span>{{ row.handoverContent || '-' }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="runStatus" label="运行状态" align="center">
          <template #default="{ row }">
            <el-tag :type="getRunStatusTag(row.runStatus)" size="small">
              {{ getRunStatusText(row.runStatus) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="status" label="交接状态" align="center">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)" size="small">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="createTime" label="创建时间" align="center" >
          <template #default="{ row }">
            <span>{{ formatDateTime(row.createTime) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center" width="280">
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="handleView(row)">
              查看
            </el-button>
            <el-button v-if="row.status === 0" type="success" link size="small" @click="handleConfirm(row)">
              确认
            </el-button>
            <el-button type="warning" link size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" link size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800px" :before-close="handleCloseDialog">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="交接时间" prop="handoverTime">
              <el-date-picker v-model="formData.handoverTime" type="datetime" placeholder="选择交接时间"
                value-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="班次" prop="shiftId">
              <el-select v-model="formData.shiftId" placeholder="请选择班次" style="width: 100%">
                <el-option v-for="item in classesOptions" :key="item.departmentId" :label="item.classesName"
                  :value="item.departmentId" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="运行状态" prop="runStatus">
              <el-select v-model="formData.runStatus" placeholder="请选择运行状态" style="width: 100%">
                <el-option label="正常" :value="1" />
                <el-option label="异常" :value="2" />
                <el-option label="维护" :value="3" />
                <el-option label="停机" :value="4" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="运行记录">
              <el-input v-model="formData.runRecord" type="textarea" :rows="3" placeholder="请输入运行记录" maxlength="500"
                show-word-limit />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="指标记录">
              <el-input v-model="formData.kpiRecord" type="textarea" :rows="3" placeholder="请输入指标记录" maxlength="500"
                show-word-limit />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="交接内容">
              <el-input v-model="formData.handoverContent" type="textarea" :rows="4" placeholder="请输入交接内容"
                maxlength="1000" show-word-limit />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="系统状态数据">
              <el-input v-model="formData.systemStatusData" type="textarea" :rows="4" placeholder="请输入系统状态数据"
                maxlength="1000" show-word-limit />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ dialogType === 'add' ? '新增' : '保存' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <el-dialog v-model="viewDialogVisible" title="交接班记录详情" width="700px" :before-close="handleCloseViewDialog">
      <div v-if="currentDetail">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="记录ID">{{ currentDetail.changeShiftsId || '-' }}</el-descriptions-item>
          <el-descriptions-item label="交班人员">{{ getUserName(currentDetail.shiftOutDispatcherId) || '-'
            }}</el-descriptions-item>
          <el-descriptions-item label="接班人员">{{ getUserName(currentDetail.shiftInDispatcherId) || '-'
            }}</el-descriptions-item>
          <el-descriptions-item label="班次">{{ getClassName(currentDetail.shiftId) || '-' }}</el-descriptions-item>
          <el-descriptions-item label="交接时间">{{ formatDateTime(currentDetail.handoverTime) || '-'
            }}</el-descriptions-item>
          <el-descriptions-item label="运行状态">
            <el-tag :type="getRunStatusTag(currentDetail.runStatus)" size="small">
              {{ getRunStatusText(currentDetail.runStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="交接状态">
            <el-tag :type="getStatusTag(currentDetail.status)" size="small">
              {{ getStatusText(currentDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(currentDetail.createTime) || '-'
            }}</el-descriptions-item>
          <el-descriptions-item label="更新时间">{{ formatDateTime(currentDetail.updateTime) || '-'
            }}</el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="交接内容" :column="1" border class="mt-3">
          <el-descriptions-item label="交接内容">
            <div class="content-text">{{ currentDetail.handoverContent || '无' }}</div>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="运行记录" :column="1" border class="mt-3">
          <el-descriptions-item label="运行记录">
            <div class="content-text">{{ currentDetail.runRecord || '无' }}</div>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions title="指标记录" :column="1" border class="mt-3">
          <el-descriptions-item label="指标记录">
            <div class="content-text">{{ currentDetail.kpiRecord || '无' }}</div>
          </el-descriptions-item>
        </el-descriptions>

        <el-descriptions v-if="currentDetail.systemStatusData" title="系统状态数据" :column="1" border class="mt-3">
          <el-descriptions-item label="系统状态">
            <div class="content-text">{{ currentDetail.systemStatusData || '无' }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <el-button @click="handleCloseViewDialog">关闭</el-button>
        <el-button v-if="currentDetail && currentDetail.status === 0" type="success"
          @click="handleConfirm(currentDetail)">
          确认接班
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import dayjs from 'dayjs'

// API引入
import {
  getUserList,
  getClassesList,
  getDispatchChangeShiftsList,
  getDispatchChangeShiftsDetail,
  addDispatchChangeShifts,
  confirmChangeShifts,
  deleteDispatchChangeShifts
} from '@/api/dispatch/affair/handover_manage'

// 搜索表单
const searchForm = reactive({
  recordType: 1, // 默认查询交班记录
  shiftId: '',
  status: '',
  handoverTime: ''
})

// 分页参数
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 下拉选项
const userOptions = ref([])
const classesOptions = ref([])

// 表格数据
const tableData = ref([])
const selectedRows = ref([])
const loading = ref(false)
const submitting = ref(false)

// 对话框控制
const dialogVisible = ref(false)
const viewDialogVisible = ref(false)
const dialogType = ref('add') // add/edit

// 当前详情
const currentDetail = ref(null)

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
  handoverTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
  shiftId: '',
  runStatus: 1,
  runRecord: '',
  kpiRecord: '',
  handoverContent: '',
  systemStatusData: ''
})

// 表单验证规则
const formRules = {
  handoverTime: [
    { required: true, message: '请选择交接时间', trigger: 'change' }
  ],
  shiftId: [
    { required: true, message: '请选择班次', trigger: 'change' }
  ],
  runStatus: [
    { required: true, message: '请选择运行状态', trigger: 'change' }
  ]
}

// 初始化数据
onMounted(() => {
  initData()
})

// 初始化数据
const initData = async () => {
  try {
    await Promise.all([
      fetchUserList(),
      fetchClassesList()
    ])
    await fetchDispatchChangeShiftsList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  }
}

// 获取用户列表
const fetchUserList = async () => {
  try {
    const res = await getUserList()
    userOptions.value = res.data || []
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 获取班次列表
const fetchClassesList = async () => {
  try {
    const res = await getClassesList()
    classesOptions.value = res.data || []
  } catch (error) {
    console.error('获取班次列表失败:', error)
    ElMessage.error('获取班次列表失败')
  }
}

// 获取交接班记录列表
const fetchDispatchChangeShiftsList = async () => {
  try {
    loading.value = true

    const params = {
      recordType: searchForm.recordType,
      shiftId: searchForm.shiftId,
      status: searchForm.status,
      handoverTime: searchForm.handoverTime,
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    const res = await getDispatchChangeShiftsList(params)

    tableData.value = res.rows || []
    pagination.total = res.total || 0
  } catch (error) {
    console.error('获取交接班记录列表失败:', error)
    ElMessage.error('获取交接班记录列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1
  fetchDispatchChangeShiftsList()
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    recordType: 1,
    shiftId: '',
    status: '',
    handoverTime: ''
  })
  pagination.currentPage = 1
  handleSearch()
}

// 处理选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增记录
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 查看详情
const handleView = async (row) => {
  try {
    const res = await getDispatchChangeShiftsDetail(row.changeShiftsId)
      currentDetail.value = res.data
      viewDialogVisible.value = true
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error('获取详情失败')
  }
}

// 编辑记录
const handleEdit = async (row) => {
  try {
    const res = await getDispatchChangeShiftsDetail(row.changeShiftsId)
      dialogType.value = 'edit'
      Object.assign(formData, {
        handoverTime: res.data.handoverTime,
        shiftId: res.data.shiftId,
        runStatus: res.data.runStatus,
        runRecord: res.data.runRecord || '',
        kpiRecord: res.data.kpiRecord || '',
        handoverContent: res.data.handoverContent || '',
        systemStatusData: res.data.systemStatusData || ''
      })
      dialogVisible.value = true
  } catch (error) {
    console.error('获取编辑数据失败:', error)
    ElMessage.error('获取编辑数据失败')
  }
}

// 确认接班
const handleConfirm = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要确认该接班记录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await confirmChangeShifts(row.changeShiftsId)
    ElMessage.success('确认成功')
    fetchDispatchChangeShiftsList()
    if (viewDialogVisible.value) {
      viewDialogVisible.value = false
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认失败:', error)
      ElMessage.error('确认失败')
    }
  }
}

// 删除记录
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该交接班记录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await deleteDispatchChangeShifts(row.changeShiftsId)
    ElMessage.success('删除成功')
    fetchDispatchChangeShiftsList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const ids = selectedRows.value.map(item => item.changeShiftsId).join(',')
    await deleteDispatchChangeShifts(ids)
    ElMessage.success('批量删除成功')
    selectedRows.value = []
    fetchDispatchChangeShiftsList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

// 批量确认
const handleBatchConfirm = async () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请选择要确认的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要确认选中的 ${selectedRows.value.length} 条记录吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    for (const row of selectedRows.value) {
      if (row.status === 0) { // 只确认待确认的记录
        await confirmChangeShifts(row.changeShiftsId)
      }
    }

    ElMessage.success('批量确认成功')
    selectedRows.value = []
    fetchDispatchChangeShiftsList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量确认失败:', error)
      ElMessage.error('批量确认失败')
    }
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    handoverTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    shiftId: '',
    runStatus: 1,
    runRecord: '',
    kpiRecord: '',
    handoverContent: '',
    systemStatusData: ''
  })
  if (formRef.value) {
    formRef.value.clearValidate()
  }
}

// 关闭对话框
const handleCloseDialog = () => {
  dialogVisible.value = false
  resetForm()
}

// 关闭查看对话框
const handleCloseViewDialog = () => {
  viewDialogVisible.value = false
  currentDetail.value = null
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    if (dialogType.value === 'add') {
      await addDispatchChangeShifts(formData)
      ElMessage.success('交接班记录新增成功')
    } else {
      // 编辑接口需要根据实际情况调整
      // await updateDispatchChangeShifts(formData)
      ElMessage.success('编辑功能开发中')
    }

    dialogVisible.value = false
    fetchDispatchChangeShiftsList()
  } catch (error) {
    console.error('提交失败:', error)
    if (error.errors) {
      return
    }
    ElMessage.error('操作失败')
  } finally {
    submitting.value = false
  }
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
  fetchDispatchChangeShiftsList()
}

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  fetchDispatchChangeShiftsList()
}

// 工具函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-'
  try {
    return dayjs(dateTimeString).format('YYYY-MM-DD HH:mm:ss')
  } catch {
    return dateTimeString
  }
}

const getUserName = (userId) => {
  if (!userId) return '-'
  const user = userOptions.value.find(item => item.id === userId)
  return user ? user.name : `用户${userId}`
}

const getClassName = (classId) => {
  if (!classId) return '-'
  const classItem = classesOptions.value.find(item => item.departmentId === classId)
  return classItem ? classItem.classesName : `班次${classId}`
}

const getRunStatusTag = (status) => {
  switch (status) {
    case 1: return 'success' // 正常
    case 2: return 'danger'  // 异常
    case 3: return 'warning' // 维护
    case 4: return 'info'    // 停机
    default: return 'info'
  }
}

const getRunStatusText = (status) => {
  switch (status) {
    case 1: return '正常'
    case 2: return '异常'
    case 3: return '维护'
    case 4: return '停机'
    default: return status || '-'
  }
}

const getStatusTag = (status) => {
  switch (status) {
    case 0: return 'warning' // 待确认
    case 1: return 'success' // 已确认
    default: return 'info'
  }
}

const getStatusText = (status) => {
  switch (status) {
    case 0: return '待确认'
    case 1: return '已确认'
    default: return status || '-'
  }
}

// 计算属性
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增交接班记录' : '编辑交接班记录'
})
</script>

<style scoped lang="scss">
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  .el-row {
    margin-bottom: 0;
  }
}

.form-actions {
  text-align: left;
}

.table-card {
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 15px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.empty-table {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.content-text {
  white-space: pre-wrap;
  word-break: break-word;
  line-height: 1.5;
  max-height: 200px;
  overflow-y: auto;
  padding: 8px;
  background: #f5f7fa;
  border-radius: 4px;
}

.mt-3 {
  margin-top: 16px;
}

:deep(.el-table) {
  .cell {
    white-space: nowrap;
    text-align: center;
  }

  th {
    text-align: center;
  }
}

:deep(.el-descriptions) {
  margin-bottom: 16px;
}

:deep(.el-descriptions__title) {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

:deep(.el-descriptions__label) {
  font-weight: 500;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}

:deep(.el-card) {
  margin-bottom: 20px;
}

:deep(.el-card):last-child {
  margin-bottom: 0;
}

@media (max-width: 768px) {
  .search-form .el-col {
    margin-bottom: 15px;
  }

  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }
}
</style>